package cn.itcast.mybatis.demo2;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.naming.InitialContext;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import cn.itcast.mybatis.pojo.User;

public class MybatisFirst {

	/**
	 * 实现对user表的增删改查
	 */
	private SqlSession sqlSession;
	
	
	@Before
	public  void init() throws IOException{
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		//使用build方法出入mybatis的核心配置文件，然后才可以创建sqlSessionFactory
		//获取sqlSessionFactory
		SqlSessionFactory build = builder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
		//获取sqlSession
		sqlSession= build.openSession();
	}
	
	
	
	/**
	 * 通过id来查询用户
	 * @throws Exception
	 */
	@Test
	public void getUserById() throws Exception {
		/**
		 * 使用两个参数的，第一个参数带表我们的sqlId
		 * 第二个参数表示我们传入的参数值
		 */
		User user = sqlSession.selectOne("getUserById", 16);
		System.out.println(user.toString());
		sqlSession.close();
	}
	
	/**
	 * 通过地址来进行模糊查询
	 * @throws Exception
	 */
	@Test
	public void getUserByAddress() throws Exception {
		List<User> userList= sqlSession.selectList("getUserByAddress", "河南");
		for (User user : userList) {
			System.out.println(user.getAddress());
		}
		sqlSession.close();
	}
	
	
	/**
	 * 插入用户
	 */
	@Test
	public void insertUser() throws Exception {
		User user = new User();
		System.out.println("用户数据的主键是"+user.getId());
		user.setAddress("天津人");
		user.setBirthday(new Date());
		user.setSex("1");
		user.setUsername("霍元甲");
		sqlSession.insert("insertUser", user);
		//注意，对于数据库的操作，除了查询，不用提交之外，增删改，都需要进行提交
		sqlSession.commit();
		System.out.println(user.getId());
		sqlSession.close();
	}
	
	/**
	 * 更新用户的操作
	 * @throws Exception
	 */
	@Test
	public void updateUser() throws Exception {
		User user = new User();
		user.setId(29);
		user.setAddress("上海");
		user.setSex("0");
		user.setUsername("杜月笙");
		sqlSession.update("updateUser", user);
		sqlSession.commit();
		sqlSession.close();
	}
	/**
	 * 删除操作，作业
	 */

}
